<template>
  <div>
    <br>
    <el-form :inline="true">
      <el-form-item label="书名">
        <el-input v-model="searchMap.name" placeholder="书名"></el-input>
      </el-form-item>
      <el-form-item label="副标题">
        <el-input v-model="searchMap.subtitle" placeholder="副标题、宣传语"></el-input>
      </el-form-item>
      <el-form-item label="作者">
        <el-input v-model="searchMap.author" placeholder="作者"></el-input>
      </el-form-item>
      <el-form-item label="出版社">
        <el-input v-model="searchMap.publishingHouse" placeholder="出版社"></el-input>
      </el-form-item>

      <el-form-item label="商品状态">
        <el-select v-model="searchMap.status" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属类目">
        <el-select v-model="searchMap.catalogId" placeholder="请选择">
          <el-option
            v-for="item in catalogList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-button type="primary" @click="fetchData()">查询</el-button>
      <el-button type="primary" @click="handleEdit('')">新增</el-button>
    </el-form>
    <el-table
      :data="list"
      border
      style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <span><h3>推荐语</h3></span>
          <mavon-editor
            class="md"
            :value="props.row.bookDetail.recommendation"
            :subfield="false"
            :defaultOpen="'preview'"
            :toolbarsFlag="false"
            :editable="false"
            :scrollStyle="true"
            :ishljs="true"></mavon-editor>
          <span><h3>简介</h3></span>
          <mavon-editor
            class="md"
            :value="props.row.bookDetail.content"
            :subfield="false"
            :defaultOpen="'preview'"
            :toolbarsFlag="false"
            :editable="false"
            :scrollStyle="true"
            :ishljs="true"></mavon-editor>
          <span><h3>作者介绍</h3></span>
          <mavon-editor
            class="md"
            :value="props.row.bookDetail.authorIntroduction"
            :subfield="false"
            :defaultOpen="'preview'"
            :toolbarsFlag="false"
            :editable="false"
            :scrollStyle="true"
            :ishljs="true"></mavon-editor>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="主键" width="80"></el-table-column>
      <el-table-column prop="name" label="书名" width="80"></el-table-column>
      <el-table-column prop="subtitle" label="副标题、宣传语" width="200"></el-table-column>
      <el-table-column label="定价" width="80">
        <template slot-scope="scope">
          {{ (scope.row.price * 0.01).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="原价" width="80">
        <template slot-scope="scope">
          {{ (scope.row.orignPrice * 0.01).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="80"></el-table-column>
      <el-table-column prop="saleNumber" label="销量" width="80"></el-table-column>
      <el-table-column prop="author" label="作者" width="100"></el-table-column>
      <el-table-column prop="publishedDate" label="出版时间" width="120">
        <template slot-scope="scope">
          {{ (scope.row.publishedDate).substring(0, scope.row.publishedDate.indexOf(' ')) }}
        </template>
      </el-table-column>
      <el-table-column prop="publishingHouse" label="出版社" width="180"></el-table-column>
      <el-table-column prop="picture" label="封面" width="160">
        <template slot-scope="scope">
          <img class="lazy" alt="封面"
               :src="scope.row.picture" width="80px" height="100px">
        </template>
      </el-table-column>
      <el-table-column prop="status" label="商品状态" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" size="small" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row.status === 2" size="small" type="info">下架</el-tag>
          <el-tag v-else-if="scope.row.status === 3" size="small" type="danger">删除</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="catalog.name" label="所属类目" width="80"></el-table-column>
      <el-table-column prop="createDate" label="创建时间" width="160"></el-table-column>
      <el-table-column prop="modifiedDate" label="修改时间" width="160"></el-table-column>

      <el-table-column
        fixed="right"
        label="操作"
        width="100">
        <template slot-scope="scope">
          <el-button @click="handleEdit(scope.row.id)" type="text" size="small">修改</el-button>
          <el-button @click="handleDelete(scope.row.id)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5,10,20]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog title="编辑" :visible.sync="dialogFormVisible">
      <el-form label-width="80px">
        <el-form-item label="书名">
          <el-input v-model="pojo.name"></el-input>
        </el-form-item>
        <el-form-item label="副标题、宣传语">
          <el-input v-model="pojo.subtitle"></el-input>
        </el-form-item>
        <el-form-item label="定价（以分为单位）">
          <el-input v-model="pojo.price"></el-input>
        </el-form-item>
        <el-form-item label="原价（以分为单位）">
          <el-input v-model="pojo.orignPrice"></el-input>
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="pojo.stock"></el-input>
        </el-form-item>
        <el-form-item label="销量">
          <el-input v-model="pojo.saleNumber"></el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="pojo.author"></el-input>
        </el-form-item>
        <el-form-item label="出版时间">
          <el-date-picker
            v-model="pojo.publishedDate"
            type="month"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="pojo.publishingHouse"></el-input>
        </el-form-item>
        <el-form-item label="封面图片">
<!--          <el-input v-model="pojo.picture"></el-input>-->
          <el-upload
            class="upload-demo"
            action="#"
            :before-upload="beforeUpload">
            <el-button size="small" type="primary">点击上传</el-button>
            <span>{{pojo.picture}}</span>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select v-model="pojo.status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属类目">
          <el-select v-model="pojo.catalog.id" placeholder="请选择">
            <el-option
              v-for="item in catalogList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="推荐语">
          <mavon-editor ref=md v-model="pojo.bookDetail.recommendation" @imgAdd="$imgAdd"
                        @imgDel="$imgDel"></mavon-editor>
        </el-form-item>
        <el-form-item label="内容简介">
          <mavon-editor ref=md2 v-model="pojo.bookDetail.content" @imgAdd="$imgAdd" @imgDel="$imgDel"></mavon-editor>
        </el-form-item>
        <el-form-item label="作者介绍">
          <mavon-editor ref=md3 v-model="pojo.bookDetail.authorIntroduction" @imgAdd="$imgAdd"
                        @imgDel="$imgDel"></mavon-editor>
        </el-form-item>
        <el-button type="primary" @click="handleSave()">保存</el-button>
        <el-button @click="dialogFormVisible = false">关闭</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import bookApi from '@/api/book'
  import catalogApi from '@/api/catalog'
  import uploadApi from '@/api/upload'

  export default {
    data() {
      return {
        pictureUrl: '',
        list: [],
        total: 0, // 总记录数
        currentPage: 1, // 当前页
        pageSize: 10, // 每页大小
        searchMap: {}, // 查询条件
        dialogFormVisible: false, // 编辑窗口是否可见
        pojo: {
          id: '',
          name: '',
          subtitle: '',
          price: '',
          orignPrice: '',
          stock: '',
          saleNumber: '',
          author: '',
          publishedDate: '',
          publishingHouse: '',
          picture: '',
          status: '',
          catalog: {
            id: '',
            name: ''
          },
          bookDetail: {
            id: '',
            recommendation: '',
            content: '',
            authorIntroduction: ''
          }
        }, // 编辑表单绑定的实体对象
        id: '', // 当前用户修改的ID
        options: [{
          value: 1,
          label: '正常'
        }, {
          value: 2,
          label: '下架'
        }, {
          value: 3,
          label: '删除'
        }], // 商品状态
        catalogList: [] // 分类列表
      }
    },
    created() {
      this.fetchData()
      this.getCatalogList()
    },
    methods: {
      beforeUpload(file) {
        // 第一步.将图片上传到服务器.
        var formdata = new FormData()
        formdata.append('image', file, 'fileName')
        uploadApi.save(formdata).then(response => {
          this.pojo.picture = response.data
          console.log(response.data)
        })
        return false // 返回false不会自动上传
      },
      fetchData() {
        bookApi.search(this.currentPage, this.pageSize, this.searchMap).then(response => {
          this.list = response.data.rows
          this.total = response.data.total
        })
      },
      handleSave() {
        bookApi.update(this.id, this.pojo).then(response => {
          this.$message({
            message: response.message,
            type: (response.flag ? 'success' : 'error')
          })
          if (response.flag) { // 如果成功
            this.fetchData() // 刷新列表
          }
        })
        this.dialogFormVisible = false // 关闭窗口
      },
      handleEdit(id) {
        this.id = id
        this.dialogFormVisible = true // 打开窗口
        if (id !== '') { // 修改
          bookApi.findById(id).then(response => {
            if (response.flag) {
              this.pojo = response.data
            }
          })
        } else {
          this.pojo = {
            id: '',
            name: '',
            subtitle: '',
            price: '',
            orignPrice: '',
            stock: '',
            saleNumber: '',
            author: '',
            publishedDate: '',
            publishingHouse: '',
            picture: '',
            status: '',
            catalog: {
              id: '',
              name: ''
            },
            bookDetail: {
              id: '',
              recommendation: '',
              content: '',
              authorIntroduction: ''
            }
          } // 清空数据
        }
      },
      handleDelete(id) {
        this.$confirm('确定要删除此纪录吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          bookApi.deleteById(id).then(response => {
            this.$message({ message: response.message, type: (response.flag ? 'success' : 'error') })
            if (response.flag) {
              this.fetchData() // 刷新数据
            }
          })
        })
      },
      getCatalogList() {
        catalogApi.getList().then(response => {
          this.catalogList = response.data
        })
      },
      handleSizeChange(size) {
        this.pageSize = size
        this.fetchData()
      },
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage
        this.fetchData()
      },
      // 绑定@imgAdd event
      $imgAdd(pos, $file) {
        // 第一步.将图片上传到服务器.
        var formdata = new FormData()
        formdata.append('image', $file)
        uploadApi.save(formdata).then(response => {
          // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
          // $vm.$img2Url 详情见本页末尾
          console.log(response.data)
          this.$refs.md.$img2Url(pos, response.data)
        })
      },
      $imgDel() {
      }
    }
  }
</script>
